package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.constants.UserConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.vos.PageResultVo;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    private IWemediaClient weMediaClient;
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 获取待审核列表
     *
     * @param dto 查询参数
     */
    @Override
    public ResponseResult<PageResultVo<ApUserRealname>> loadListByStatus(AuthDto dto) {
        // 1. 校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 分页条件检查
        dto.checkParam();

        // 2.分页根据状态精确查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        Page<ApUserRealname> pageR = page(page, lambdaQueryWrapper);

        //3.结果返回
        PageResultVo<ApUserRealname> pageResultVo = new PageResultVo<>();
        if (pageR == null || pageR.getRecords() == null) {

            return ResponseResult.okResult(pageResultVo);
        }

        pageResultVo.setRecords(pageR.getRecords());
        pageResultVo.setPage(pageR.getCurrent());
        pageResultVo.setSize(pageR.getSize());
        pageResultVo.setTotal(pageR.getTotal());

        return ResponseResult.okResult(pageResultVo);
    }


    @Override
    public ResponseResult<AppHttpCodeEnum> updateStatus(AuthDto dto, Short status) {
        // 1. 参数校验
        if (dto == null || dto.getId() == null || status == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        // 3.如果审核状态是9，就是成功，需要创建自媒体账户
        if (UserConstants.PASS_AUTH.equals(status)) {
            ResponseResult<AppHttpCodeEnum> responseResult = createWmUserAndAuthor(dto);
            if (responseResult != null) {
                return responseResult;
            }
        }

        // 2. 如果用户状态是9, 需要创建自媒体用户,
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体用户和作者信息
     *
     * @param dto 用户信息
     * @return 返回空代表成功, 否则失败
     */
    private ResponseResult<AppHttpCodeEnum> createWmUserAndAuthor(AuthDto dto) {
        Integer userRealnameId = dto.getId();
        // 查询用户认证信息
        ApUserRealname apUserRealname = getById(userRealnameId);
        if (apUserRealname == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 查询app端用户信息
        Integer userId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectById(userId);
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 创建自媒体账户
        WmUser wmUser = weMediaClient.findWmUserByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setCreatedTime(new Date());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            weMediaClient.saveWmUser(wmUser);
        }
        apUser.setFlag((short) 1); // 创建自媒体账户后, 将用户状态从普通用户更改为 -> 自媒体人
        int isUpdate = apUserMapper.updateById(apUser); // 更新用户信息
        return isUpdate > 0 ? null : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
